<?php

namespace app\lnksns\controller\api;

use app\lnksns\lib\JwtAuth;
use app\lnksns\lib\SuPengJun;
use app\lnksns\lib\TencentLbs;
use app\lnksns\model\DynamicModel;
use app\lnksns\model\MessageModel;
use app\lnksns\model\UserModel;
use app\lnksns\model\UserFollowModel;
use app\lnksns\model\UserLikeDynamicModel;
use app\lnksns\service\DynamicService;
use app\lnksns\service\UserService;
use EasyWeChat\Factory;
use lite\service\ConfigService;
use think\facade\Db;
use think\Request;

class User
{
    public function wx_empower(Request $request)
    {

        $code = $request->post('code');
        if (!$code) return error('授权失败', 500001);

        $config = [
            'app_id' => ConfigService::get('lnksns', 'lnk_app_id', ''),
            'secret' => ConfigService::get('lnksns', 'lnk_app_secret', ''),
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->auth->session($code);
        if (!$response['openid']) return error('授权失败', 500001);

        $info = UserModel::where('weixin_openid', $response['openid'])->field(UserService::user_find())->find();
        if (!$info) {
            $model = [
                'name' => '用户' . rand(100000, 999999),
                'avatar' => $request->domain() . '/static/images/avatar.png',
                'weixin_openid' => $response['openid'],
                'ip' => $request->ip(),
                'create_time' => time()
            ];
            $res = TencentLbs::ip($request->ip());
            if ($res['status'] == 0) {
                $model = SuPengJun::ip_text($model, $res['result']);
            }
            (new UserModel)->insert($model);
            $info = UserModel::where('weixin_openid', $response['openid'])->field(UserService::user_find())->find();
        }
        $info = UserService::user_other($info);
        $data['info'] = $info;
        $data['token'] = JwtAuth::signToken($info['id']);
        return success('success', $data);
    }

    public function user_refresh_info(Request $request)
    {
        $uid = $request->uid;
        $info = UserModel::where('id', $uid)->field(UserService::user_find())->find();
        $info = UserService::user_other($info);
        $data['info'] = $info;
        $data['token'] = JwtAuth::signToken($info['id']);
        return success('success', $data);
    }

    public function edit_user_info(Request $request)
    {
        $uid = $request->uid;
        $model = [];
        $model['name'] = $request->post('name');
        $model['avatar'] = $request->post('avatar');
        $model['gender'] = $request->post('gender');
        $model['age'] = $request->post('age');
        $model['career'] = $request->post('career');
        $model['update_time'] = time();
        UserModel::where('id', $uid)->update($model);

        return success('修改成功 🎉');
    }

    public function user_bind_mobile(Request $request)
    {
        $uid = $request->uid;
        $code = $request->post('code');
        if (!$code) return error('授权失败', 500001);

        $config = [
            'app_id' => ConfigService::get('lnksns', 'lnk_app_id', ''),
            'secret' => ConfigService::get('lnksns', 'lnk_app_secret', ''),
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $response = $app->phone_number->getUserPhoneNumber($code);

        if ($response['errmsg'] == 'ok') {
            $model['mobile'] = $response['phone_info']['phoneNumber'];
            $model['update_time'] = time();
            UserModel::where('id', $uid)->update($model);

            $data = UserModel::where('id', $uid)->field(UserService::user_find())->find();
            $data = UserService::user_other($data);

            return success('操作成功 🎉', $data);
        } else {
            return error('授权失败', 500001);
        }
    }

    public function user_refresh_ip(Request $request)
    {
        $uid = $request->uid;
        $res = TencentLbs::ip($request->ip());
        if ($res['status'] == 0) {
            $model = SuPengJun::ip_text([], $res['result']);
            UserModel::where('id', $uid)->update($model);

            $data = UserModel::where('id', $uid)->field(UserService::user_find())->find();
            $data = UserService::user_other($data);

            return success('刷新成功 🎉', $data);
        } else {
            return error('刷新失败', 500001);
        }
    }

    public function user_details(Request $request)
    {
        $uid = $request->uid;
        $user_id = $request->get('user_id', 0);
        $data = UserModel::where('id', $user_id)->field(UserService::user_find())->find();
        if (!$data) return error('未找到用户或用户异常！', 500101);
        $data = UserService::user_other($data, $uid);
        UserModel::where('id', $user_id)->update([
            'weigh' => Db::raw('weigh+1')
        ]);
        return success('成功', $data);
    }

    public function user_publish_content(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type');
        $user_id = $request->get('user_id', 0);
        $status = [0, 1];
        if ($user_id > 0) {
            $uid = $user_id;
            $status = [1];
        }
        if ($type == 0) {
            $data = DynamicModel::where('user_id', $uid)
                ->whereIn('status', $status)
                ->order('id', 'desc')
                ->field(DynamicService::dynamic_find())
                ->paginate(6)->toArray();
            if ($data) $data = DynamicService::dynamic_map($data, $user_id > 0, $request->uid);
        } else {
            $ids = UserLikeDynamicModel::where('user_id', $uid)
                ->where('status', 1)
                ->order('id', 'desc')
                ->column('dynamic_id');
            $ids_ordered = implode(',', $ids);
            if (count($ids)) {
                $data = DynamicModel::where('status', 1)
                    ->whereIn('id', $ids)
                    ->orderRaw("FIELD(id, $ids_ordered)")
                    ->field(DynamicService::dynamic_find())
                    ->paginate(6)->toArray();
                if ($data) $data = DynamicService::dynamic_map($data, $user_id > 0, $request->uid);
            }
        }

        return success('成功', $data ?? '');
    }

    public function follow_user(Request $request)
    {
        $uid = $request->uid;
        $uname = $request->post('uname');
        $user_id = $request->post('user_id');
        $is_follow = $request->post('is_follow');
        if ($user_id == $uid) return error('您不能关注您自己', 500201);
        if ($is_follow) {
            UserFollowModel::where('user_id', $uid)
                ->where('follow_user_id', $user_id)
                ->delete();
        } else {
            UserFollowModel::insert([
                'user_id' => $uid,
                'follow_user_id' => $user_id,
                'create_time' => time()
            ]);
            $message = $uname . ' 关注了你。';
            $avatar_url = '/pages/user/details?id=' . $uid;
            (new MessageModel())->send($user_id, '收到关注', $message, $uid, '', $avatar_url);
            UserModel::where('id', $user_id)->update([
                'weigh' => Db::raw('weigh+10')
            ]);
        }
        return success('成功', '');
    }

    public function user_follow(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type');
        if ($type == 1) {
            $data = UserFollowModel::where('user_id', $uid)
                ->order('id', 'desc')
                ->field('id,follow_user_id')
                ->paginate(15)->toArray();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['user'] = UserModel::where('id', $v['follow_user_id'])
                    ->field('id,name,avatar')
                    ->find();
                $data['data'][$k]['is_follow'] = UserFollowModel::where('user_id', $v['follow_user_id'])
                    ->where('follow_user_id', $uid)
                    ->count() ? true : false;
            }
        } else {
            $data = UserFollowModel::where('follow_user_id', $uid)
                ->order('id', 'desc')
                ->field('id,user_id')
                ->paginate(15)->toArray();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['user'] = UserModel::where('id', $v['user_id'])
                    ->field('id,name,avatar')
                    ->find();
                $data['data'][$k]['is_follow'] = UserFollowModel::where('user_id', $uid)
                    ->where('follow_user_id', $v['user_id'])
                    ->count() ? true : false;
            }
        }

        return success('成功', $data);
    }

}
